#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
const int N = 1005;
int n, m;
struct node {
	int v, w;
	node (int vi, int wi) {
		v = vi;
		w = wi;
	}
};
vector <node> g[N];
int d[N];
queue <int> q;
bool inq[N];
int num[N];
bool SPFA (int s) {
	memset (d, -0x3f, sizeof(d));
	d[s] = 0;
	q.push(s);
	inq[s] = 1;
	num[s] = 1;
	while (!q.empty()) {
		int u = q.front();
		q.pop();
		inq[u] = 0;
		for (unsigned i = 0; i < g[u].size(); i++) {
			int v = g[u][i].v;
			int dis = g[u][i].w;
			if (d[v] < d[u] + dis) {
				d[v] = d[u] + dis;
				q.push(v);
				num[v]++;
				if (num[v] > n) {
					return false;
				}
			}
		}
	}
	return true;
}
int main() {
	scanf ("%d%d", &n, &m);
	int x, y, z;
	for (int i = 1; i <= m; i++) {
		scanf ("%d%d%d", &x, &y, &z);
		if (z == -1) {
			g[y].push_back(node(x, 1));
		} else if (z == 1) {
			g[x].push_back(node(y, 1));
		} else {
			g[x].push_back(node(y, 0));
			g[y].push_back(node(x, 0));
		}
	}
	for (int i = 1; i <= n; i++) {
		g[0].push_back(node(i, 0));
	}
	bool tmp = SPFA(0);
	int ans = 0;
	if (!tmp) {
		printf ("NO\n");
		return 0;
	}
	for (int i = 1; i <= n; i++) {
		ans = max (ans, d[i]);
	}
	printf ("%d\n", ans);
	return 0;
}